package com.carleasoft.mps.cms.business.message.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.carleasoft.mps.cms.business.message.bean.entity.MessageNote;
import com.carleasoft.mps.cms.business.message.bean.entity.MessageReceive;
import com.carleasoft.mps.cms.business.message.bean.entity.MessageReceiveUser;
import com.carleasoft.mps.cms.business.message.bean.po.*;
import com.carleasoft.mps.cms.business.message.bean.vo.MessageNoteDetailVo;
import com.carleasoft.mps.cms.business.message.bean.vo.MessageNoteVo;
import com.carleasoft.mps.cms.business.message.bean.vo.ResponseReceivedDetailVo;
import com.carleasoft.mps.cms.business.message.bean.vo.ResponseReceivedVo;
import com.carleasoft.mps.cms.business.message.dao.MessageNoteMapper;
import com.carleasoft.mps.cms.business.message.service.MessageNoteService;
import com.carleasoft.mps.cms.business.message.service.MessageReceiveService;
import com.carleasoft.mps.cms.business.message.service.MessageReceiveUserService;
import com.carleasoft.mps.cms.business.personal.bean.entity.PersonalCenterEntity;
import com.carleasoft.mps.cms.business.personal.service.PersonalCenterService;
import com.carleasoft.mps.cms.business.user.bean.UserSkill;
import com.carleasoft.mps.cms.business.user.service.UserSkillService;
import com.carleasoft.mps.core.user.ThreadUserContext;
import com.carleasoft.mps.core.user.UserCacheData;
import com.carleasoft.mps.core.utils.IBeanUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 留言基础表 服务实现类
 * </p>
 *
 * @author fan
 * @since 2023-05-17
 */
@Service
public class MessageNoteServiceImpl extends ServiceImpl<MessageNoteMapper, MessageNote> implements MessageNoteService {

    @Autowired
    private MessageReceiveService messageReceiveService;
    @Autowired
    private MessageReceiveUserService messageReceiveUserService;
    @Autowired
    private PersonalCenterService personalCenterService;//savePersonalCenter() PersonalCenterEntity personalCenterEntity
    @Autowired
    private UserSkillService userSkillService;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean massageNoteAdd(MessageNoteAddPo messageNoteAddPo) {
        UserCacheData user = ThreadUserContext.getCurrentCacheUser();
        MessageNote messageNote = new MessageNote();
        BeanUtils.copyProperties(messageNoteAddPo,messageNote);
        messageNote.setMessageCode(UUID.randomUUID().toString().replaceAll("-",""));
        messageNote.setCreatePersonCode(user.getUserCode());
        messageNote.setCreatePersonName(user.getUserName());
        messageNote.setCreateTime(LocalDateTime.now());
        messageNote.setUpdatePersonCode(user.getUserCode());
        messageNote.setUpdatePersonName(user.getUserName());
        messageNote.setUpdateTime(LocalDateTime.now());
        messageNote.setStatus(1);
        PersonalCenterEntity personalCenterEntity = new PersonalCenterEntity();
        if (messageNoteAddPo.getMessageType()==1){//心理咨询
            personalCenterEntity.setMessage("你收到一条心理咨询留言，可进入管理后台查看详细内容");
        }
        if (messageNoteAddPo.getMessageType()==2){//法律援助
            personalCenterEntity.setMessage("你收到一条法律援助留言，可进入管理后台查看详细内容");
        }
        personalCenterEntity.setIsRead(1);
        personalCenterEntity.setType(2);
        personalCenterEntity.setUserCode(messageNoteAddPo.getReceiveCode());
        personalCenterEntity.setResourceType(1);
        personalCenterService.savePersonalCenter(personalCenterEntity);
        return this.save(messageNote);
    }

    @Override
    public boolean massageNoteDelete(MessageNote messageNote) {
        IBeanUtil.paramVerify(messageNote,"messageCode");
        LambdaQueryWrapper<MessageNote> eq = Wrappers.lambdaQuery(MessageNote.class).eq(MessageNote::getMessageCode, messageNote.getMessageCode());
        return this.remove(eq);
    }

    @Override
    public Page<MessageNoteVo> pageQuery(MessageNotePageQueryPo messageNotePageQueryPo) {
        UserCacheData user = ThreadUserContext.getCurrentCacheUser();
        messageNotePageQueryPo.setUserCode(user.getUserCode());
        //获取专家
        Integer num = userSkillService.count(new QueryWrapper<UserSkill>().eq("USER_TYPE",2).eq("USER_CODE",user.getUserCode()));
        Integer num1 = userSkillService.count(new QueryWrapper<UserSkill>().eq("USER_TYPE",3).eq("USER_CODE",user.getUserCode()));
        if (num>0 || num1>0){
            messageNotePageQueryPo.setSign(1);
        }else {
            messageNotePageQueryPo.setSign(0);
        }
        Page page = new Page(messageNotePageQueryPo.getCurrent(),messageNotePageQueryPo.getSize());
        List<String> list = this.baseMapper.myCanViewMessageNoteCodes(user.getUserCode());//权限
        if (list==null || list.size()<=0){
            list = new LinkedList<>();
            list.add("-1");
        }
        messageNotePageQueryPo.setMessageCodes(list);
        return this.baseMapper.pageQuery(page,messageNotePageQueryPo);
    }

    @Override
    public Page<MessageNoteVo> pageQuery1(MessageNotePageQueryPo messageNotePageQueryPo) {
        Page page = new Page(messageNotePageQueryPo.getCurrent(),messageNotePageQueryPo.getSize());
        return this.baseMapper.pageQuery1(page,messageNotePageQueryPo);
    }

    @Override
    public MessageNoteDetailVo massageNoteDetail(MessageNote messageNote) {
        MessageNoteDetailVo messageNoteDetailVo = new MessageNoteDetailVo();
        IBeanUtil.paramVerify(messageNote,"messageCode");
//        LambdaQueryWrapper<MessageNote> eq = Wrappers.lambdaQuery(MessageNote.class).eq(MessageNote::getMessageCode, messageNote.getMessageCode());
//        MessageNote one = this.getOne(eq);
        messageNoteDetailVo = this.baseMapper.selectMessageNoteDetail(messageNote.getMessageCode());
        if (messageNoteDetailVo!=null){
            messageNoteDetailVo.setMessageReceiveList(messageReceiveService.list(new QueryWrapper<MessageReceive>().eq("MESSAGE_CODE",messageNote.getMessageCode())));
            messageNoteDetailVo.setMessageReceiveUserList(messageReceiveUserService.list(new QueryWrapper<MessageReceiveUser>().eq("MESSAGE_CODE",messageNote.getMessageCode())));
        }
        return messageNoteDetailVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean massageNoteDeal(NoteDealPo noteDealPo) {
        UserCacheData user = ThreadUserContext.getCurrentCacheUser();
        MessageNote one = this.getOne(new QueryWrapper<MessageNote>().eq("MESSAGE_CODE", noteDealPo.getMessageCode()));
        MessageReceive messageReceive = new MessageReceive();
        BeanUtils.copyProperties(noteDealPo,messageReceive);
        messageReceive.setReceiveCode(UUID.randomUUID().toString().replaceAll("-",""));
        messageReceive.setCreatePersonCode(user.getUserCode());
        messageReceive.setCreatePersonName(user.getUserName());
        messageReceive.setCreateTime(LocalDateTime.now());
        List<String> messageReceiveUsers = noteDealPo.getMessageReceiveUsers();
        List<MessageReceiveUser> messageReceiveUserList = new LinkedList<>();
        if (messageReceiveUsers!=null && messageReceiveUsers.size()>0){
            messageReceiveUsers.stream().forEach(a->{
                MessageReceiveUser messageReceiveUser = new MessageReceiveUser();
                messageReceiveUser.setMessageCode(noteDealPo.getMessageCode());
                messageReceiveUser.setUserCode(a);
                messageReceiveUserList.add(messageReceiveUser);
            });
            messageReceiveUserService.saveBatch(messageReceiveUserList);
        }
        //设置留言状态
        UpdateWrapper<MessageNote> up = new UpdateWrapper<>();
        up.set("STATUS",noteDealPo.getStatus());
        up.eq("MESSAGE_CODE",noteDealPo.getMessageCode());
        this.update(up);
        PersonalCenterEntity personalCenterEntity = new PersonalCenterEntity();
        if (one.getMessageType()==1){//心理咨询
            personalCenterEntity.setMessage("你的心理咨询留言有反馈了,可进入管理后台查看详细内容");
        }
        if (one.getMessageType()==2){//法律援助
            personalCenterEntity.setMessage("你的心理咨询留言有反馈了，可进入管理后台查看详细内容");
        }
        personalCenterEntity.setIsRead(1);
        personalCenterEntity.setType(2);
        personalCenterEntity.setUserCode(one.getCreatePersonCode());
        personalCenterEntity.setResourceType(2);
        personalCenterService.savePersonalCenter(personalCenterEntity);
        return messageReceiveService.save(messageReceive);
    }

    @Override
    public boolean massageNoteAppoint(MassageNoteAppointPo massageNoteAppointPo) {
        List<String> personCodes = massageNoteAppointPo.getPersonCodes();
        List<MessageReceiveUser> messageReceiveUserList = new LinkedList<>();
        personCodes.stream().forEach(a->{
            MessageReceiveUser messageReceiveUser = new MessageReceiveUser();
            messageReceiveUser.setUserCode(a);
            messageReceiveUser.setMessageCode(massageNoteAppointPo.getMessageCode());
            messageReceiveUserList.add(messageReceiveUser);
        });
        return messageReceiveUserService.saveBatch(messageReceiveUserList);
    }

    @Override
    public Page<ResponseReceivedVo> responseReceived( ResponseReceivedPagePo responseReceivedPagePo) {
        Page page = new Page(responseReceivedPagePo.getCurrent(),responseReceivedPagePo.getSize());
        UserCacheData user = ThreadUserContext.getCurrentCacheUser();
        return this.baseMapper.responseReceived(page,user.getUserCode());
    }

    @Override
    public ResponseReceivedDetailVo responseReceivedDetail(MessageReceive messageReceive) {
        IBeanUtil.paramVerify(messageReceive,"receiveCode");
        ResponseReceivedDetailVo responseReceivedDetailVo = new ResponseReceivedDetailVo();
        MessageReceive one = messageReceiveService.getOne(new QueryWrapper<MessageReceive>().eq("RECEIVE_CODE", messageReceive.getReceiveCode()));
        if (one!=null){
            BeanUtils.copyProperties(one,responseReceivedDetailVo);
            responseReceivedDetailVo.setMessageNote(this.getOne(new QueryWrapper<MessageNote>().eq("MESSAGE_CODE",one.getMessageCode())));
        }
        return responseReceivedDetailVo;
    }

    @Override
    public Page<MessageNote> massageNoteWait(MassageNoteWaitPo massageNoteWaitPo) {
        Page page = new Page(massageNoteWaitPo.getCurrent(),massageNoteWaitPo.getSize());
        UserCacheData user = ThreadUserContext.getCurrentCacheUser();
//        QueryWrapper<MessageNote> qw = new QueryWrapper<>();
//        qw.in("MESSAGE_TYPE",1,2);
//        qw.eq("RECEIVE_CODE",user.getUserCode());
//        qw.eq("STATUS",1);
//        List<MessageNote> list = this.list(qw);
        return this.baseMapper.massageNoteWait(page,user.getUserCode());
    }

    @Override
    public List<MessageNoteVo> queryList(MessagePersonalCenterQueryListPo messagePersonalCenterQueryListPo) {
        UserCacheData user = ThreadUserContext.getCurrentCacheUser();
        messagePersonalCenterQueryListPo.setLoginCode(user.getUserCode());
        return this.baseMapper.queryList(messagePersonalCenterQueryListPo);
    }

    @Override
    public HashMap<String, Object> statisticalAnalysisMessageNote(StatisticalAnalysisMessageNotePo statisticalAnalysisMessageNotePo) {
        HashMap<String, Object> returnMap = new HashMap<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy");
        String theYear = simpleDateFormat.format(new Date());
        Integer all = this.baseMapper.statisticalAnalysisMessageNote(statisticalAnalysisMessageNotePo.getType(), null,theYear);
        Integer ed = this.baseMapper.statisticalAnalysisMessageNote(statisticalAnalysisMessageNotePo.getType(), 3,theYear);
        returnMap.put("all",all);
        returnMap.put("ed",ed);
        return returnMap;
    }
}
